#!/bin/bash

# TLS证书生成脚本
# 用于生成开发和测试环境的自签名证书

set -e

CERT_DIR="./certs"
CA_KEY="$CERT_DIR/ca.key"
CA_CERT="$CERT_DIR/ca.crt"
SERVER_KEY="$CERT_DIR/server.key"
SERVER_CSR="$CERT_DIR/server.csr"
SERVER_CERT="$CERT_DIR/server.crt"

echo "🔐 生成TLS证书用于OpenCloudOS节点管理工具"
echo "============================================"

# 创建证书目录
mkdir -p "$CERT_DIR"

# 1. 生成CA私钥
echo "1. 生成CA私钥..."
openssl genrsa -out "$CA_KEY" 4096

# 2. 生成CA证书
echo "2. 生成CA证书..."
openssl req -new -x509 -days 365 -key "$CA_KEY" -out "$CA_CERT" \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=OpenCloudOS/OU=NodeManager/CN=NodeManager-CA"

# 3. 生成服务器私钥
echo "3. 生成服务器私钥..."
openssl genrsa -out "$SERVER_KEY" 4096

# 4. 生成服务器证书签名请求
echo "4. 生成服务器证书签名请求..."
openssl req -new -key "$SERVER_KEY" -out "$SERVER_CSR" \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=OpenCloudOS/OU=NodeManager/CN=localhost"

# 5. 创建扩展配置文件
cat > "$CERT_DIR/server.ext" << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = *.localhost
DNS.3 = node-server
DNS.4 = *.node-server
IP.1 = 127.0.0.1
IP.2 = ::1
IP.3 = 0.0.0.0
EOF

# 6. 使用CA签名生成服务器证书
echo "5. 使用CA签名生成服务器证书..."
openssl x509 -req -in "$SERVER_CSR" -CA "$CA_CERT" -CAkey "$CA_KEY" \
    -CAcreateserial -out "$SERVER_CERT" -days 365 \
    -extfile "$CERT_DIR/server.ext"

# 7. 验证证书
echo "6. 验证证书..."
openssl x509 -in "$SERVER_CERT" -text -noout | grep -A1 "Subject Alternative Name" || true

# 8. 设置权限
chmod 600 "$CA_KEY" "$SERVER_KEY"
chmod 644 "$CA_CERT" "$SERVER_CERT"

echo ""
echo "✅ TLS证书生成完成！"
echo "证书位置："
echo "  CA证书: $CA_CERT"
echo "  CA私钥: $CA_KEY"
echo "  服务器证书: $SERVER_CERT"
echo "  服务器私钥: $SERVER_KEY"
echo ""
echo "📋 证书信息："
openssl x509 -in "$SERVER_CERT" -subject -issuer -dates -noout
echo ""
echo "⚠️  注意: 这些是自签名证书，仅用于开发和测试环境！"
echo "   生产环境请使用正式的CA签发的证书。"
